package com.softcits.email;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.softcits.email.auth.AuthEntryPoint;
import com.softcits.email.auth.JwtAuthenticationFilter;
import com.softcits.email.auth.JwtLoginFilter;
import com.softcits.email.auth.RestAuthenticationAccessDeniedHandler;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }
    public static void main(String[] args) {
        WebSecurityConfig config = new WebSecurityConfig();
        config.passwordEncoder();
    }
    
    @Autowired
    private UserDetailsService userDetailsService;
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.cors().and().csrf().disable().formLogin().and().authorizeRequests().antMatchers("/login")
//        .permitAll().anyRequest().authenticated();
        http.cors().and().csrf().disable().authorizeRequests()
        .antMatchers("/*/**").permitAll()
                .antMatchers("/*").permitAll()
                .antMatchers("/").permitAll()
        .antMatchers("/login").permitAll()
        .antMatchers("/user/login").permitAll()
        .antMatchers("/user/register").permitAll()
        .antMatchers("/*.html").permitAll()
        .antMatchers("/js/**").permitAll()
        .antMatchers("/css/**").permitAll()
        .antMatchers("/user/email").permitAll()
        .anyRequest().authenticated()
        .anyRequest()
        .access("@rbacauthorityservice.hasPermission(request,authentication)")
        .and()
        .addFilter(new JwtLoginFilter(authenticationManager()))
        .addFilter(new JwtAuthenticationFilter(authenticationManager()))
        .exceptionHandling().accessDeniedHandler(new RestAuthenticationAccessDeniedHandler())
        .authenticationEntryPoint(new AuthEntryPoint())
        .and()
        .headers().frameOptions().sameOrigin();
    }
}
